<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->

<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="name" :label="t('role.name')">
        <el-input v-model="formData.name" :placeholder="t('role.name')"></el-input>
      </el-form-item>
      <el-form-item prop="comment" :label="t('role.comment')">
        <el-input v-model="formData.comment" :placeholder="t('role.comment')"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item size="small" :label="t('role.menuList')">
            <el-tree :data="menuList" :props="defaultProps" node-key="id" ref="menuListTreeRef" accordion show-checkbox> </el-tree>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size="small" :label="t('role.deptList')">
            <el-tree :data="deptList" :props="defaultProps" node-key="id" ref="deptListTreeRef" accordion show-checkbox> </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import { ElMessage, FormRules } from 'element-plus';
import type { ResType } from '@/utils/request';
import type { ElForm, ElTree } from 'element-plus';
import { ref, reactive, nextTick, watch } from 'vue';
import { systemApi } from '@/api/system';

// #region 类型
type FormData = {
  id: string;
  name: string;
  menuIdList: string[];
  deptIdList: string[];
  comment: string;
};

// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const menuListTreeRef = ref<InstanceType<typeof ElTree>>();
const deptListTreeRef = ref<InstanceType<typeof ElTree>>();
const formRef = ref<InstanceType<typeof ElForm> | null>(null);

const { t } = useI18n();

const dialogId = ref('0');
// 页面配置
const options = reactive({
  loading: false,
  visible: false,
});
// 表单数据
const formData = reactive<FormData>({
  id: '',
  name: '',
  menuIdList: [],
  deptIdList: [],
  comment: '',
});
// 部门列表
const deptList = ref([]);
// 菜单列表
const menuList = ref([]);
const defaultProps = ref({ label: 'name', children: 'children' });

const formRules = reactive<FormRules<FormData>>({
  name: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
});

// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

// 获取菜单列表
const getMenuList = async () => {
  systemApi.getMenuSelect().then((res) => {
    if (res?.code === 0) {
      Object.assign(menuList.value, res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};
// 获取权限列表
const getDeptList = async () => {
  systemApi.getDeptList().then((res) => {
    if (res?.code === 0) {
      Object.assign(deptList.value, res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 获取信息
const getInfo = async () => {
  options.loading = true;
  systemApi.getRoleInfo(formData.id).then(async (res) => {
    if (res?.code === 0) {
      await nextTick();
      Object.assign(formData, res.data);
      formData.menuIdList.forEach((item) => menuListTreeRef.value?.setChecked(item, true, false));
      deptListTreeRef.value?.setCheckedKeys(formData.deptIdList);
    } else {
      ElMessage.error(res.msg);
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

const init = async () => {
  options.visible = true;
  options.loading = true;
  await nextTick();
  formRef.value?.resetFields();
  menuListTreeRef.value?.setCheckedKeys([]);
  deptListTreeRef.value?.setCheckedKeys([]);
  await Promise.all([getMenuList(), getDeptList()]).then(() => {
    if (formData.id) {
      getInfo();
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

// 新增角色
function insertRole() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .insertRole(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新角色
function updatetRole() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .updatetRole(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}

// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      formData.menuIdList = [...(menuListTreeRef.value?.getHalfCheckedKeys() as string[]), ...(menuListTreeRef.value?.getCheckedKeys() as string[])];
      formData.deptIdList = deptListTreeRef.value?.getCheckedKeys() as string[];
      let res;
      if (formData.id) {
        res = await updatetRole();
      } else {
        res = await insertRole();
      }
      if (res?.code !== 0) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      }
    }
  });
}
// 防抖
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>
